package net.sf.jhighlighter.autocomplete;

import java.awt.Rectangle;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

/**
 * An auto completion component that can be added to any JTextComponent. It's not finished.
 * @author paul
 */
public class FAutoComplete {

    JTextComponent textArea;
    JPopupMenu pop;

    public FAutoComplete(JTextComponent textComp) {
        textArea = textComp;
        pop = new JPopupMenu();
    }

    /**
     * Makes the auto-completion popup visible at the bottom of the caret.
     * @throws BadLocationException
     */
    public void show() throws BadLocationException {
        try {
            Rectangle r = textArea.modelToView(textArea.getCaretPosition());
            // Shows pop on this component and gets the x and y values for the text
            pop.show(textArea, r.x, textArea.getCaret().getMagicCaretPosition().y +
                    textArea.getFontMetrics(textArea.getFont()).getHeight());
        } catch (NullPointerException ex) {
            System.out.println(ex);
        }
    }

    
    public static String checkWord(String line, int caretPosition) {
        // String line, int caretPosition
        //Gets line up to the caret
        String subString = line.substring(0, caretPosition);

        int start = -1;
        int i = subString.length() - 1;
        for (int ii = i; ii < subString.length(); i--) {

            if (isDelimiter(subString.substring(i - 1, i))) {
                start = i;
                break;
            }
        }
        return subString.substring(start, subString.length());
    }

    static boolean isDelimiter(String character) {
        String operands = ".;:()\\\"\'[]{}+-/%<=>!?&|^~*";
        if (Character.isWhitespace(character.charAt(0)) ||
                operands.indexOf(character) != -1) {
            return true;
        } else {
            return false;
        }
    }
}
